
#include <BLine>

#include "member_BTextual.h"

using namespace BWE;

member_BTextual::member_BTextual(BTextual* textual)
{
	boss = textual;
	originAlign = Align_Center;
	align = Align_Center;
	glyphSize = 1;
	dirtyText = true;
}
member_BTextual::~member_BTextual()
{

}

void member_BTextual::freshTextSize()
{
	items.resize(text.count());
	textSize.set(0, glyphSize);
	if (font && text.size())
	{
		BVector point = down * glyphSize * 0.8f;
		BReal rowWidth = 0;
		BReal width_mult = glyphSize / font->size();
		for (auto it = text.begin(); it != text.end(); it++)
		{
			int count = it.count();
			if (it == '\n')
			{
				textSize.height() += glyphSize;
				point = down * textSize.height();
				rowWidth = 0;
			}

			BSize codeSize = font->codeSize(*it);
			BReal cw = codeSize.width() * width_mult;
			BReal ch = codeSize.height() * width_mult;

			CodeQuad& item = items[count];
			item.quad.a() = point - down * ch;
			item.quad.b() = point;
			item.quad.c() = point + right * cw;
			item.quad.d() = point - down * ch + right * cw;
			item.image = 0;
			item.imageQuad = item.quad;

			CodeInfo* info = font_member(font)->getCodeInfo(*it);
			if (info)
			{
				item.image = font->image(*it);
				BReal left = info->left * width_mult;
				BReal top = info->top * width_mult;

				BReal bw = item.image->width() * width_mult;
				BReal bh = item.image->height() * width_mult;

				item.imageQuad.a() = point + right * left;
				item.imageQuad.b() = point + right * left + down * bh;
				item.imageQuad.c() = item.imageQuad.b() + right * bw;
				item.imageQuad.d() = item.imageQuad.a() + right * bw;
				item.imageQuad -= down * top;
			}
			point += right * cw;
			rowWidth += cw;
			if (textSize.width() < rowWidth)
			{
				textSize.width() = rowWidth;
			}
		}
	}
}
void member_BTextual::rebuild()
{
	BRealSize realSize = size;
	if (realSize.width() <= 0)
		realSize.width() = textSize.width();
	if (realSize.height() <= 0)
		realSize.height() = textSize.height();
	quad.a().reset();
	quad.b() = down * realSize.height();
	quad.c() = down * realSize.height() + right * realSize.width();
	quad.d() = right * realSize.width();
	BReal hrw = realSize.width() * BReal(0.5);
	BReal hrh = realSize.height() * BReal(0.5);
	if (originAlign == Align_Center)
	{
		quad -= down * hrh;
		quad -= right * hrw;
	}

	BRealRect rect(realSize);
	BRealPoint pos = rect.align(align, textSize).pos();
	textQuad.a() = quad.a() + right * pos.x() + down * pos.y();
	textQuad.b() = down * textSize.height();
	textQuad.c() = down * textSize.height() + right * textSize.width();
	textQuad.d() = right * textSize.width();
}
